<?php
/**
 * Created by PhpStorm.
 * 楼小二用户分组
 * User: caicm
 * Date: 2017/2/18
 * Time: 9:18
 */

namespace SDXApi\Model;
use Think\Model;

class LouxiaoerGroupModel extends Model
{
    /*
     * 添加分组
     * Created By caicm
     * @param int $louxiaoer_id 楼小二id
     * @param string $name 组名称
     * return mixed
     */
    public function addGroup($louxiaoer_id, $name){

        $data = array(
            'louxiaoer_id' => $louxiaoer_id,
            'group_name' => $name,
            'add_time' => gmtime()
        );

        return $this->data($data)->add();
    }

    /*
     * 查询分组
     * Created By caicm
     * @param int $louxiaoer_id 楼小二id
     * @param string $name 组名称
     * return mixed
     */
    public function findGroup($louxiaoer_id, $name){

        $where = array(
            'louxiaoer_id' => $louxiaoer_id,
            'group_name' => $name
        );

        return $this->where($where)->find();

    }


    /*
     * 计算分组数量
     * Created By caicm
     * @param int $louxiaoer_id 楼小二id
     * @param int $group_id 分组id
     * return number
     */
    public function findGroupCount($louxiaoer_id, $group_id=0){

        $where = array(
            'louxiaoer_id' => $louxiaoer_id,
            'group_id' => $group_id
        );

        if($group_id ==0) unset($where['group_id']);

        return $this->where($where)->count();
    }

    /*
     * 群组列表
     * Created By caicm
     * @param int $louxiaoer_id 楼小二id
     * @param mixed $limit 分页
     * return number
     */
    public function findGroupList($louxiaoer_id, $limit){

        $where = array(
            'louxiaoer_id' => $louxiaoer_id
        );

        $field = "group_name as name,group_id as id";

        return $this->field($field)->where($where)->order('CONVERT( name USING gbk ) COLLATE gbk_chinese_ci ASC')->limit($limit)->select();

    }



    /*
     * 删除群组
     * Created By caicm
     * @param int $louxiaoer_id 楼小二id
     * @param int $group_id 群组id
     * return mixed
     */
    public function delGroup($louxiaoer_id,  $group_id){

        $where = array(
            'louxiaoer_id' => $louxiaoer_id,
            'group_id' => $group_id
        );

        return $this->where($where)->delete();

    }

    /*
     * 会员可添加的群组列表
     * Created By caicm
     * @param int $louxiaoer_id
     * @param int $member_id
     * return mixed
     */
    public function get_group_list_with_member($louxiaoer_id, $member_id){

        $where = array(
            'g.louxiaoer_id' => $louxiaoer_id
        );

        return $this
            ->alias('g')
            ->field('g.group_id as id,g.group_name as name,count(u.group_id) as count_member')
            ->join('left join  sdx_louxiaoer_group_user as u on g.group_id=u.group_id  ')
            ->where($where)
            ->group('g.group_id')
            ->having('SUM(IF(u.louxiaoer_user_id = '.$member_id.', 1, 0)) =0')
            ->select();


    }







}